<?php

class ConsumeModel extends DBModel
{
	protected $_table = '{{consume}}';
	protected $_id = 'cid';
	
	public function getItemIdByUserID($userid, $select = '*')
	{
		$where['select'] = $select;
		$where['condition'] = 'userid = :userid';
		$params[':userid'] = $userid;
		return $this->findAll($where, $params);
	}
	
	public function getMyConsume($userid, $consumetype)
	{
		$where['from'] = '{{consume}} c';
		$where['select'] = 'c.sorpuserid userid,c.howmuch,c.itemid,c.createtime,c.consumetype,u.truename,i.title itemname';
		$where['condition'] = 'c.userid = :userid';
		$params = array(':userid' => $userid);
		$where['join'] = 'left join {{user}} u on u.userid = c.sorpuserid 
						  left join {{item}} i on i.itemid = c.itemid';
		if ($consumetype > 0) {
			$where['condition'] .= ' AND c.consumetype = :consumetype';
			$params[':consumetype'] = $consumetype;
		}
		$where['order'] = 'c.createtime DESC';
		return $this->findAll($where, $params);
	}
	
	public function getConsume($userid)
	{
		$where['from'] = '{{consume}} c';
		$where['select'] = 'c.sorpuserid userid,c.howmuch,c.itemid,c.createtime,u.truename,i.title itemname';
		$where['condition'] = 'c.userid = :userid';
		$where['join'] = 'left join {{user}} u on u.userid = c.sorpuserid 
						  left join {{item}} i on i.itemid = c.itemid';
		$params = array(':userid' => $userid);
		$where['order'] = 'c.createtime DESC';
		return $this->findAll($where, $params);
	}
	
	public function isExist($userid, $itemid)
	{
		$where['select'] = 'cid';
		$where['condition'] = 'userid = :userid and itemid = :itemid';
		$params[':userid'] = $userid;
		$params[':itemid'] = $itemid;
		return $this->findScalar($where, $params);
	}
	
	public function getFansHowmuch($userid, $sorpuserid, $consumetype)
	{
		$where['select'] = 'sum(howmuch)';
		$where['condition'] = 'userid = :userid and sorpuserid = :sorpuserid and consumetype = :consumetype';
		$params = array(':userid' => $userid, ':sorpuserid' => $sorpuserid, ':consumetype' => $consumetype);
		return $this->findScalar($where, $params);
	}
	
	public function getStateByItemId($item_id)
	{
		//$where['select'] = 'sum(howmuch) suportmoney, count(*) suportcount';
		$where['select'] = 'count(*) suportcount';
		$where['condition'] = 'itemid = :itemid';
		$where['group'] = 'itemid';
		$params = array(':itemid' => $item_id);
		return $this->find($where, $params);
	}
}